package example.prototype.greatestsage;

import lombok.Data;

import java.io.*;
import java.util.Date;

/**
 * 齐天大圣
 */
@Data
public class TheGreatestsage extends Monkey implements Cloneable, Serializable {

    // 金箍棒
    private GoldRingedStaff goldRingedStaff;

    /**
     * 从石头蹦出来
     */
    public TheGreatestsage() {
        this.goldRingedStaff = new GoldRingedStaff();
        this.birthday = new Date();
        this.height = 150;
        this.weight = 30;
    }

    public void change() {
        TheGreatestsage copy = (TheGreatestsage) clone();
        System.out.println("大圣本尊的生日：" + this.getBirthday().getTime());
        System.out.println("大圣clone的生日：" + copy.getBirthday().getTime());
        System.out.println("大圣本尊和clone的是否是同一个对象：" + (copy == this));
        System.out.println("大圣本尊的和clone的金箍棒是否同一个对象：" + (copy.getGoldRingedStaff() == this.goldRingedStaff));
    }

    /**
     * 分身技能- 金箍棒和生日一样---浅拷贝
     *
     * @return
     */
    public Object clone() {
        // 金箍棒和生日一样---浅拷贝
        //return super.clone();

        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            TheGreatestsage copy = (TheGreatestsage) ois.readObject();
            copy.setBirthday(new Date());
            return copy;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
